package com.wifi.io.mirror.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.wifi.io.mirror.R;
import com.wifi.io.mirror.common.DvActivity;
import com.wifi.io.mirror.common.DvAsyncTask;
import com.wifi.io.mirror.service.SearchService;
import com.wifi.io.mirror.service.SearchService.MyBinder;
import com.wifi.io.mirror.util.DataCenter;
import com.wifi.io.mirror.util.JsonUtil;
import com.wifi.io.mirror.util.NetUtil;

public class MainUI extends DvActivity {
	public Context context;
	//private final static String WIFI_IO_URL = "http://113.11.197.191/message.php?message=";
	private final static String WIFI_IO_URL = "http://memo.wifi.io/message.php?message=";
	private EditText editMessage;
	private Button btnSend;
	private Button btnOpen;
	private ImageView imgPersion;
	private TextView txtLog;
	private String message;
	
	private static boolean persionExistFlag = false;
	private SearchService mService; 
	private Handler handler = new Handler(); 
	//edit
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE); 		
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_main_ui);
		context = this;
		
		InitUI();
		// 开启后台服务，定时请求是否有人，实现简单的推送
		StartSearchService();
		// 开启计时器判断是否该显示镜中人像
		OpenTimer();
	}
	
	public void InitUI(){
		btnSend = (Button)findViewById(R.id.btnSend);
		btnOpen = (Button)findViewById(R.id.btnOpen);
		editMessage = (EditText)findViewById(R.id.edtMessage);
		txtLog = (TextView)findViewById(R.id.txtLog);
		imgPersion = (ImageView)findViewById(R.id.imgPeople);
		
		BtnOnClickFunc btnFunc = new BtnOnClickFunc();
		btnSend.setOnClickListener(btnFunc);
		btnOpen.setOnClickListener(btnFunc);
		
	}

	@Override
	public void UpdateUI(String key) {
		super.UpdateUI(key);
		boolean result = JsonUtil.getResult(key);
		if(result){
			txtLog.setText(message + " was sent successfully");
		} else {
			txtLog.setText(message + " was sent fail");
		}
	}
	
	public void SetPersionVisible(){
		if(DataCenter.getCenter().isExist()){
			findViewById(R.id.context).setBackgroundResource(R.drawable.mirror2);
        	imgPersion.setVisibility(View.VISIBLE);
        } else {
        	findViewById(R.id.context).setBackgroundResource(R.drawable.mirror1);
        	imgPersion.setVisibility(View.INVISIBLE);
        }
	}
		
	public void OpenTimer(){		  
		handler.postDelayed(task,500);
        handler.post(task);
	    
	}
	
	private Runnable task = new Runnable() {  
        public void run() {   
                handler.postDelayed(this,100);
                SetPersionVisible();
        }   
    };
	
	private class BtnOnClickFunc implements OnClickListener{
		@Override
		public void onClick(View v) {
			if(v.getId() == R.id.btnSend){
				if(editMessage.getText().toString().equals("")) return;
				SendMessage();
				editMessage.setText("");
				HideKeyboard();
			} else if(v.getId() == R.id.btnOpen){
			}
		}
	}
	
	private void SendMessage(){  
		if(!NetUtil.checkNet(this)) return;
		message = editMessage.getText().toString();
		try {
			message = URLEncoder.encode(message,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		DvAsyncTask.CreateTask(this, "Main").execute(message);
    }  
	
	private void HideKeyboard(){
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm.isActive()) { 
			imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS); 
		}
	}
	
	private void StartSearchService(){
		Intent intent = new Intent(this,SearchService.class);
        startService(intent);
        //bindService(intent, conn, Context.BIND_AUTO_CREATE);
	}
	
	public void setDisplayPersion(boolean is){
		ImageView img = (ImageView)findViewById(R.id.imgPeople);
		if(is){
			findViewById(R.id.context).setBackgroundResource(R.drawable.mirror1);
			img.setVisibility(View.VISIBLE);
			
		} else {
			findViewById(R.id.context).setBackgroundResource(R.drawable.mirror1);
			img.setVisibility(View.INVISIBLE);
			
		}
	}
	
	private ServiceConnection conn = new ServiceConnection() {   
        @Override
        public void onServiceDisconnected(ComponentName name) {
        	mService = null;
        }

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			MyBinder binder = (MyBinder)service;
            SearchService bindService = binder.getService();
            bindService.MyMethod();
            //flag = true;
		}
    };
    
    
    
    
	

}